﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DestinationOperations;
using System.Text.RegularExpressions;

namespace Beginning
{
    public partial class AddDestination : Form
    {
        public AddDestination()
        {
            InitializeComponent();
            CBBindControls();
            cbWeekdaysBindControls();
            cbBusesBindControls();
        }

        private void cbWeekdaysBindControls()
        {
            string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
                                "Saturday", "Sunday" };

            lbDaysOfWeek.DataSource = days.ToList();
        }

        private void CBBindControls()
        {
            var settlements = from s in DestinationOperations.DAO.GetAllSettlements()
                              orderby s.SettlementName
                              select s.SettlementName;

            cbFirst.DataSource = settlements.ToList();
            cbLast.DataSource = settlements.ToList();
        }

        public void cbBusesBindControls()
        {
            var buses = from b in DAO.GetAllBuses()
                        select b.BusRegNumber;

            cbBuses.DataSource = buses.ToList();
        }

        private long GetSettlementID(string name)
        {
            return DestinationOperations.DAO.GetSettlementID(name);
        }

        private void btnAddSettlement_Click(object sender, EventArgs e)
        {
            groupBoxNewSettlement.Enabled = true;
        }

        private void btnInsertSettlement_Click(object sender, EventArgs e)
        {
            bool confirmation =
                MessageBox.Show("A new settlement added!", "Message",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK;

            if (confirmation)
            {
                DestinationOperations.DAO.AddSettlement(txtNewSettlementName.Text);
                CBBindControls();
                txtNewSettlementName.Text = string.Empty;
                groupBoxNewSettlement.Enabled = false;
            }
        }

        private void btnCancelSettlement_Click(object sender, EventArgs e)
        {
            groupBoxNewSettlement.Enabled = false;
        }

        private void rbCustom_CheckedChanged(object sender, EventArgs e)
        {
            lbDaysOfWeek.Visible = true;
        }

        private void rbWeekdays_CheckedChanged(object sender, EventArgs e)
        {
            lbDaysOfWeek.Visible = false;
        }

        private void rbWeekend_CheckedChanged(object sender, EventArgs e)
        {
            lbDaysOfWeek.Visible = false;
        }

        private void rbEveryDay_CheckedChanged(object sender, EventArgs e)
        {
            lbDaysOfWeek.Visible = false;
        }

        private void btnAddDestination_Click(object sender, EventArgs e)
        {
            int lastTimeTo;
            string destinationName = cbFirst.Text + "-" + cbLast.Text;
            string scheduleDayOfWeek = "";

            DestinationOperations.DAO.AddDestination(destinationName);

            var destID = from d in DestinationOperations.DAO.GetAllDestinations()
                         where d.DestistionName == destinationName
                         select d.DestinationID;

            if (rbEveryDay.Checked)
            {
                scheduleDayOfWeek = "Every Day";
            }
            else if (rbWeekdays.Checked)
            {
                scheduleDayOfWeek = "Monday - Friday";
            }
            else if (rbWeekend.Checked)
            {
                scheduleDayOfWeek = "Saturday, Sunday";
            }
            else if (rbCustom.Checked)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var selectedItem in lbDaysOfWeek.SelectedItems)
                {
                    sb.Append(selectedItem.ToString() + " ");
                }

                scheduleDayOfWeek = sb.ToString();
            }

            SheduleType scheduleType = new SheduleType();
            DestinationOperations.DAO.AddScheduleType(scheduleDayOfWeek);

            StartHour startHour = new StartHour();
            startHour.DestinationID = destID.First();
            startHour.StartHourValue = ((controlStartHour.Hours * 60) + controlStartHour.Minutes);
            startHour.SheduleTypeID =
                DestinationOperations.DAO.GetScheduleTypeID(scheduleDayOfWeek);

            DestinationOperations.DAO.AddStartHour(startHour);

            //Adding the first point of the destination
            DestinationOperations.DAO.AddWayStation(GetSettlementID(cbFirst.Text),
                destID.First(), 0, 0, 0, 0, 0);

            lastTimeTo = ((controlLastTimeTo.Hours * 60) + (controlLastTimeTo.Minutes));

            //Adding the last point of the destination
            DestinationOperations.DAO.AddWayStation(GetSettlementID(cbLast.Text),
                destID.First(), Convert.ToInt32(txtLastDistTo.Text), lastTimeTo,
                0, Convert.ToDecimal(txtLastPriceTo.Text), 1);

            bool info =
            MessageBox.Show("A new destination added!", "Destination Added", MessageBoxButtons.OK,
                MessageBoxIcon.Information) == DialogResult.OK;

            if (info)
            {
                frmMain main = new frmMain();
                main.Show();
                this.Hide();
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            frmMain main = new frmMain();
            main.Show();
            this.Hide();
        }


        #region Validation
        private void txtLastDistTo_Validating(object sender, CancelEventArgs e)
        {
            ValidateLastDistTo();
        }

        private void txtLastPriceTo_Validating(object sender, CancelEventArgs e)
        {
            ValidateLastPriceTo();
        }

        private void txtNewSettlementName_Validating(object sender, CancelEventArgs e)
        {
            ValidateNewSettlement();
        }

        private bool ValidateLastDistTo()
        {
            if (IsLastDistToValid(txtLastDistTo.Text))
            {
                epValidateData.SetError(txtLastDistTo, "");
                return true;
            }
            else
            {
                epValidateData.SetError(txtLastDistTo, "Not a valid distance!");
                return false;
            }
        }

        private bool IsLastDistToValid(string distance)
        {
            try
            {
                if (Int32.Parse(distance) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch(FormatException)
            {
                return false;
            }
        }

        private bool ValidateLastPriceTo()
        {
            if (IsLastPriceToValid(txtLastPriceTo.Text))
            {
                epValidateData.SetError(txtLastPriceTo, "");
                return true;
            }
            else
            {
                epValidateData.SetError(txtLastPriceTo, "Not a valid price!");
                return false;
            }
        }

        private bool IsLastPriceToValid(string price)
        {
            try
            {
                if (Decimal.Parse(price) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (FormatException)
            {
                return false;
            }
        }

        private bool ValidateNewSettlement()
        {
            if (IsNewSettlementValid(txtNewSettlementName.Text))
            {
                epValidateData.SetError(txtNewSettlementName, "");
                return true;
            }
            else
            {
                epValidateData.SetError(txtNewSettlementName, "Not a valid name format!");
                return true;
            }
        }

        private bool IsNewSettlementValid(string settlement)
        {
            string pattern = @"[A-Z]{1}[a-z]+";
            Regex regex = new Regex(pattern);
            Match match = regex.Match(settlement);

            if (match.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
    }
}
